#include "qfilecachedmemory.h"


QFileCachedMemory::QFileCachedMemory()
:QFile(FILE_CACHE_NAME)
{
}

QFileCachedMemory::~QFileCachedMemory()
{
}


QStringList QFileCachedMemory::get(const QString& parameters)
{
	QStringList memory;
	if(open(QIODevice::ReadOnly))
	{
		QTextStream stream(this);
		QString line = stream.readLine();
		while(!line.isNull())
		{
			if(line.contains(parameters))
			{
				line.remove(parameters);
				memory = line.split(FILE_CACHE_SEPARATOR);
				break;
			}				
			line = stream.readLine();
		}
		close();
	}
	return memory;
}

void QFileCachedMemory::add(const QString& parameter,QStringList& add)
{
	QString all;
	add.removeDuplicates();
	if(open(QIODevice::ReadOnly))
	{
		QTextStream stream(this);
		all = stream.readAll();
		close();
	}
	if(open(QIODevice::WriteOnly))
	{
		if(all.contains(parameter))
		{
			QString line = all.mid(all.indexOf(parameter)).section("::",0,0);
			all.remove(line);
			all.append(line.insert(line.indexOf("\n"),add.join(FILE_CACHE_SEPARATOR)));
		}
		else
			all.append(QString(parameter+add.join(FILE_CACHE_SEPARATOR)+"\n"));
		QTextStream write(this);
		write << all;
		close();
	}
}

void QFileCachedMemory::replace(const QString& parameter,QStringList& add)
{
	QString all;
	add.removeDuplicates();
	if(open(QIODevice::ReadOnly))
	{
		QTextStream stream(this);
		all = stream.readAll();
		close();
		if(open(QIODevice::WriteOnly))
		{
			if(all.contains(parameter))
			{
				QString line = all.mid(all.indexOf(parameter)).section("::",0,0);
				all.remove(line);
				all.append(parameter+add.join(FILE_CACHE_SEPARATOR)+"\n");
			}
			else
				all.append(QString(parameter+add.join(FILE_CACHE_SEPARATOR)+"\n"));
			QTextStream write(this);
			write << all;
			close();
		}
	}
}